package com.serkol.abmanager;

import com.alibaba.fastjson.JSON;
import com.serkol.abmanager.bean.Result;
import com.serkol.abmanager.component.TokenAdminUtils;
import com.serkol.abmanager.config.ConstantHeader;
import com.serkol.abmanager.constant.ResultConstant;
import com.serkol.abmanager.entity.AdminToken;
import com.serkol.abmanager.libraries.IpUtil;
import com.serkol.abmanager.service.UsersService;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@Configuration
@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class ApplicationFilter implements Filter {

    @Resource
    private TokenAdminUtils adminUtils;
    @Resource
    private UsersService service;


    @Resource
    private IpUtil ipUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("SpringBoot Start");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;


        Result result = new Result();

/*     response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,token");//这里“Access-Token”是我要传到后台的内容key
        response.setHeader("Access-Control-Expose-Headers", "*");*/
        String type = request.getHeader("Content-Type");
        String method = request.getMethod();
      //  System.out.println("Ppppppppppppppp:" + method);
        if (method.equals("POST")) {


            String terminal1 = request.getHeader("terminal");
            if (terminal1 == null) {
                terminal1 = "0";
            }
            int terminal = Integer.parseInt(terminal1);
            String ipAddr = ipUtil.getIpAddr(request);
            ConstantHeader.setTerminal(terminal);
            ConstantHeader.setIp(ipAddr);


            String authorization = request.getHeader("Authorization");
          //  System.out.println("-----------------------------------authorization-------------------------------------");
            StringBuffer requestURL = request.getRequestURL();
            boolean flag = false;
            if (requestURL.toString().indexOf("api/login/login") != -1) {
                flag = true;
            }
          //  System.out.println(requestURL);
        //    System.out.println(authorization.isEmpty());

            if (!flag) {
                if (authorization != null) {
                    if (!authorization.trim().isEmpty()) {
                        System.out.println(authorization);
                        AdminToken admin = adminUtils.getAdmin(authorization);
                        System.out.println(admin);
                        if (admin != null) {
                            request.getSession().setAttribute("admin", admin);
                            ConstantHeader.setAdminToken(admin);

                            filterChain.doFilter(request, response);
                        } else {
                            getRturn(result, response);
                            // request.getRequestDispatcher("api/login/usererror").forward(request, response);
                        }
                    } else {
                        getRturn(result, response);
                    }
                } else {
                    // request.getRequestDispatcher("api/login/usererror").forward(request, response);
                    getRturn(result, response);
                }
            } else {
                filterChain.doFilter(request, response);
            }
        } else {

            filterChain.doFilter(request, response);
        }


        //   System.out.println(token);


    }

    private void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        System.out.println("SpringBoot Stop");
    }

    private void getRturn(Result result, HttpServletResponse response) throws IOException {
        result.setStatus(ResultConstant.TOKEN);
        PrintWriter writer = null;
        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(response.getOutputStream(),
                    "UTF-8");
            writer = new PrintWriter(osw, true);
            String jsonStr = JSON.toJSONString(result);
            writer.write(jsonStr);
            writer.flush();
            writer.close();
            osw.close();
        } catch (UnsupportedEncodingException e) {
            //  logger.error("过滤器返回信息失败:" + e.getMessage(), e);
        } catch (IOException e) {
            //logger.error("过滤器返回信息失败:" + e.getMessage(), e);
        } finally {
            if (null != writer) {
                writer.close();
            }
            if (null != osw) {
                osw.close();
            }
        }
        return;

    }


}

